import time
import json
from fastapi import Request
from fastapi.responses import JSONResponse


async def get_time(request: Request, call_next):
    now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    response = await call_next(request)

    if response.headers['content-type'] == 'application/json':
        # 获取响应内容
        body = [
            section async for section in response.__dict__['body_iterator']
        ]
        # 解析成 JSON 对象
        response_body = json.loads(body[0])

        # 添加时间到响应中
        response_body['now_time'] = now_time
        response_body['code'] = response.status_code

        # 创建一个新的响应
        response = JSONResponse(content=response_body,
                                status_code=response.status_code)

    return response
